<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="88px">
      <el-form-item label="模块名称" prop="moduleName">
        <el-input
          v-model="queryParams.moduleName"
          placeholder="请输入模块名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="角色名称" prop="roleName">
        <el-input
          v-model="queryParams.roleName"
          placeholder="请输入角色名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:module:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:module:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:module:remove']"
        >删除</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="moduleList" @selection-change="handleSelectionChange" :row-class-name="tableRowClassName">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="模块名称" align="center" prop="moduleName" />
      <el-table-column label="关联表名" align="center" prop="tableName" />
      <el-table-column label="角色名称" align="center" prop="roleName" />
      <el-table-column label="数据权限范围" align="center" prop="dataScope">
        <template slot-scope="scope">
          <span>{{ dataScopeFormat(scope.row) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="自定义权限" align="center" prop="scopeExpr">
        <template slot-scope="scope">
          <span>{{ scope.row.dataScope === 5 ? scope.row.scopeExpr : '无' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="等级" align="center" prop="level" />
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:module:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:module:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改模块对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="模块名称" prop="moduleName">
          <el-input v-model="form.moduleName" placeholder="请输入模块名称" />
        </el-form-item>
        <el-form-item label="关联表名" prop="tableName">
          <el-input v-model="form.tableName" placeholder="请输入关联表名" />
        </el-form-item>
        <el-form-item label="角色名称" prop="roleName">
          <el-select v-model="form.roleName" placeholder="请选择角色名称" filterable style="width: 100%" @change="onRoleChange">
            <el-option
              v-for="opt in roleOptions"
              :key="opt.value"
              :label="opt.label"
              :value="opt.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="权限范围" prop="dataScope">
          <el-select v-model="form.dataScope" placeholder="请选择数据权限范围" style="width: 100%">
            <el-option label="全部数据权限" :value="1" />
            <el-option label="本部门及以下数据权限" :value="2" />
            <el-option label="本部门数据权限" :value="3" />
            <el-option label="仅本人数据权限" :value="4" />
            <el-option label="自定义数据权限" :value="5" />
          </el-select>
        </el-form-item>
        <el-form-item label="自定义权限" prop="scopeExpr" v-if="form.dataScope === 5">
          <el-input v-model="form.scopeExpr" placeholder="请输入自定义权限表达式" />
        </el-form-item>
        <el-form-item label="等级" prop="level">
          <el-input-number v-model="form.level" :min="0" :max="99" controls-position="right" style="width: 100%" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio
              v-for="dict in dict.type.sys_normal_disable"
              :key="dict.value"
              :label="dict.value"
            >{{ dict.label }}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listModule, getModule, delModule, addModule, updateModule } from '@/api/system/module'
import { listRole } from '@/api/system/role'

export default {
  name: 'Module',
  dicts: ['sys_normal_disable'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 模块表格数据
      moduleList: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        moduleName: undefined,
        roleName: undefined
      },
      // 角色下拉选项
      roleOptions: [],
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        moduleName: [
          { required: true, message: '模块名称不能为空', trigger: 'blur' }
        ],
        tableName: [
          { required: true, message: '关联表名不能为空', trigger: 'blur' }
        ],
        roleName: [
          { required: true, message: '角色名称不能为空', trigger: 'change' }
        ],
        dataScope: [
          { required: true, message: '数据权限范围不能为空', trigger: 'change' }
        ],
        level: [
          { required: true, message: '等级不能为空', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.getList()
  },
  methods: {
    // 加载角色下拉，附加“默认权限”
    async loadRoleOptions() {
      try {
        const res = await listRole({ pageNum: 1, pageSize: 999, status: 0 })
        const rows = (res && res.rows) ? res.rows : []
        // 选项包含 roleId，value 仍为 roleName（保持现有表单字段）
        const opts = rows.map(r => ({ label: r.roleName, value: r.roleName, roleId: r.roleId }))
        // 追加“默认权限”，roleId 置为 null
        opts.unshift({ label: '默认权限', value: '默认权限', roleId: 0 })
        this.roleOptions = opts
      } catch (e) {
        // 失败也提供基础选项，保证可用
        this.roleOptions = [{ label: '默认权限', value: '默认权限', roleId: 0 }]
      }
    },
    // 角色选择变化时，写入隐藏的 roleId
    onRoleChange(val) {
      const hit = this.roleOptions.find(o => o.value === val)
      this.form.roleId = hit ? hit.roleId : undefined
    },
    /** 查询模块列表 */
    getList() {
      this.loading = true
      listModule(this.queryParams).then(response => {
        this.moduleList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        moduleId: undefined,
        moduleName: undefined,
        tableName: undefined,
        roleName: undefined,
        roleId: undefined,
        dataScope: 1,
        scopeExpr: undefined,
        level: 0,
        status: '0',
        remark: undefined
      }
      this.resetForm('form')
    },
    dataScopeFormat(row) {
      if (row.dataScope === 1) {
        return '全部'
      } else if (row.dataScope === 2) {
        return '本部门及下级'
      } else if (row.dataScope === 3) {
        return '本部门'
      } else if (row.dataScope === 4) {
        return '仅本人'
      } else if (row.dataScope === 5) {
        return '自定义'
      }
      return ''
    },
    // 表格行样式
    tableRowClassName({ row, rowIndex }) {
      if (row.roleName === '默认权限') {
        return 'default-permission-row'
      }
      return ''
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm')
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.moduleId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    async handleAdd() {
      this.reset()
      await this.loadRoleOptions()
      this.open = true
      this.title = '添加模块'
    },
    /** 修改按钮操作 */
    async handleUpdate(row) {
      this.reset()
      await this.loadRoleOptions()
      const moduleId = row.moduleId || this.ids
      const response = await getModule(moduleId)
      this.form = response.data
      // 若后端未返回 roleId，根据 roleName 从选项回填
      if ((this.form.roleId === undefined || this.form.roleId === null) && this.form.roleName) {
        const hit = this.roleOptions.find(o => o.value === this.form.roleName)
        if (hit) this.form.roleId = hit.roleId
      }
      this.open = true
      this.title = '修改模块'
    },
    /** 提交按钮 */
    submitForm: function() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          if (this.form.moduleId !== undefined) {
            updateModule(this.form).then(response => {
              this.$modal.msgSuccess('修改成功')
              this.open = false
              this.getList()
            })
          } else {
            addModule(this.form).then(response => {
              this.$modal.msgSuccess('新增成功')
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const moduleIds = row.moduleId || this.ids
      this.$modal.confirm('是否确认删除模块编号为"' + moduleIds + '"的数据项？').then(function() {
        return delModule(moduleIds)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess('删除成功')
      }).catch(() => {})
    }
  }
}
</script>

<style>
.el-table .default-permission-row {
  background-color: #b5cfed !important;
}
.el-table .default-permission-row:hover > td {
  background-color: #b5cfed !important;
}
.el-table--enable-row-hover .el-table__body tr.default-permission-row:hover > td {
  background-color: #b5cfed !important;
}
</style>
